/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bugsandcritters;

/**
 *
 * @author Robert Gibbons
 */

import java.awt.*;

public class GameManager extends Thread
{

    public static GameManager self;
    public static GameWindow gameWindow;
    private static long LastNanoTime;
    public static long DeltaTime;
    
    public Image BufferImage;
    public Graphics BufferGraphics;
    
    long TimeSinceLastDraw;
    long MaxDrawTime = 1000000000/100;
    
    public static Boolean Paused = false;
    public static GridWorld MyGrid;
    public static HudManager MyHud;
    
    
    
    Graphics  g;
    
    private void onBegin()
    {
       
        
        gameWindow= new GameWindow();
        gameWindow.setVisible(true);
        MyGrid = new GridWorld();
        MyHud = new HudManager();
        
         BufferImage = gameWindow.createImage(gameWindow.getSize().width,
                 gameWindow.getSize().height);
         BufferGraphics = BufferImage.getGraphics();
    }
    
    
    public void Draw()
    {
        if(TimeSinceLastDraw>MaxDrawTime)
            if(g!=null)
            {
                if(BufferGraphics != null)
                {
                    TimeSinceLastDraw=0;
                    BufferGraphics.setColor(Color.BLACK);
                    BufferGraphics.fillRect(0,0,GameWindow.Width,GameWindow.Height);  

                    MyGrid.Draw(BufferGraphics);
                    MyHud.Draw(BufferGraphics);
                }
                g.drawImage(BufferImage, 0, 0, null);
            }
    }
    
    private void Update()
    {
        if(!Paused)
            MyGrid.Update();
        MyHud.Update();
        
    }
    
    @Override
    public void run()
    {
        //this.setPriority(10);
        
        self=this;
        onBegin();
        g = GameWindow.MyBox.getGraphics();
        LastNanoTime = System.nanoTime();
        
           while(true)
           {  
               DeltaTime = System.nanoTime() - LastNanoTime;
               TimeSinceLastDraw+=DeltaTime;
               LastNanoTime = System.nanoTime();
               Update();
               Draw();
           }
    }
        

}
    

